<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>自定义表</title>
        <#include "/pubHeadStyle.html">
        <link rel="stylesheet" href="${ctx}/css/form.css">
    </head>
    <body>
        <form action="" class="layui-form">
            <div class="layui-btn-container" style="padding:20px 10px 8px 10px">
                <p class="layui-btn layui-btn-sm" id="save"><i class="layui-icon layui-icon-file"></i>保存</p>
                <a class="layui-btn layui-btn-sm" id="moveUp"><i class="layui-icon layui-icon-upload-circle"></i>上移</a>
                <a class="layui-btn layui-btn-sm" id="moveDown"><i class="layui-icon layui-icon-download-circle"></i>下移</a>
                <a class="layui-btn layui-btn-sm" id="revert"><i class="layui-icon layui-icon-return"></i>返回</a>
            </div>

            <div class="layui-row">
                <div class="layui-row" style="margin-bottom:15px;">
                    <table>
                        <tr>
                            <td>
                                <label class="layui-form-label" style="width: auto">表名: </label>
                            </td>
                            <td>
                                <input type="text" name="tableName" id="tableName" class="layui-input" readonly/>
                            </td>
                            <td>
                                <label class="layui-form-label" style="width: auto">注释: </label>
                            </td>
                            <td>
                                <input type="text" name="tableDesc" id="tableDesc" class="layui-input"/>
                            </td>
                            <td>
                                <label class="layui-form-label" style="width: auto">是否主表: </label>
                            </td>
                            <td class="mainTableRadio">
                                <input type="radio" name="mainTable" value="1" title="主表" checked=""
                                       style="margin-left:5px;">
                            </td>
                            <td>
                                <label class="layui-form-label" style="width: auto">主键: </label>
                            </td>
                            <td style="">
                                <select name="pKey" id="pKey" style="margin-left:5px;">
                                </select>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </form>
        <div class="editExternalTable">
            <table id="fieldList" lay-filter="fieldList"></table>
        </div>


        <script type="text/html" id="operation">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        </script>
        <script>
            layui.config({
                base: serverPath.formPath + staticPath.formPath //静态资源所在路径
            }).extend({
                index: 'index' //主入口模块
            }).use(['index', 'form', 'jquery', 'commons', 'table', 'setter'], function () {
                var form = layui.form;
                var layer = layui.layer;
                var table = layui.table;
                var $ = layui.$;
                var commons = layui.commons;
                var setter = layui.setter;

                var tableName = "${tableName}";//表名
                var dataSource = "${dataSource}";//数据源别名
                var fieldList = [];
                form.render();
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath + 'table/getTableFields',
                    type: "post",
                    dataType: 'json',
                    data: {"tableName": tableName, "dataSource": dataSource},
                    success: function (data) {
                        fieldList = data.data["fieldList"];
                        var table = data.data["table"];
                        var pkList = data.data["pkList"];
                        //给表名和注释赋值
                        $("#tableName").val(table["tableName"]);
                        $("#tableDesc").val(table["tableDesc"]);
                        //根据fieldList拼接select option
                        if (fieldList.length > 0) {
                            var text = "";
                            for (var i = 0; i < fieldList.length; i++) {
                                text += "<option value='" + fieldList[i]["fieldName"] + "'>" + fieldList[i]["fieldDesc"] + "</option>"
                            }
                            $("#pKey").append(text);
                            form.render('select');
                        }
                        //让主键默认选中
                        if (pkList.length > 0) {
                            $("#pKey option[value='" + pkList[0]["name"] + "']").attr("selected", "selected");
                        }
                        //渲染table
                        loadTable(fieldList);

                    }
                });

                function tableCheckboxData(oldData) {
                    $('.editExternalTable [name="isRequired"]').each(function (i, item) {
                        oldData[i].isRequired = $(this)[0].checked ? 1 : 0;
                    });
                    $('.editExternalTable [name="isList"]').each(function (i, item) {
                        oldData[i].isList = $(this)[0].checked ? 1 : 0;
                    });
                    $('.editExternalTable [name="isFlowVar"]').each(function (i, item) {
                        oldData[i].isFlowVar = $(this)[0].checked ? 1 : 0;
                    });
                    return oldData;
                }

                //保存
                $("#save").click(function () {
                    var tableName = $("#tableName").val();
                    var tableDesc = $("#tableDesc").val();
                    var isMain = 1;
                    var pkField = $('#pKey option:selected').val();
                    var tableForm = {
                        "tableName": tableName,
                        "tableDesc": tableDesc,
                        "isMain": isMain,
                        "pkField": pkField,
                        "dsAlias": dataSource
                    };
                    var tableData = tableCheckboxData(table.cache.fieldList);



                    $.ajax({
                        url: serverPath.formPath + setter.formLinkPath + 'table/saveExtTable',
                        type: "post",
                        dataType: 'json',
                        data: {"table": JSON.stringify(tableForm), "fields": JSON.stringify(tableData)},
                        success: function (data) {
                            if (data.code == 0) {
                                //关闭所有弹框
                                layer.alert(data.msg, {skin: 'btn-class'}, function () {
                                    commons.bulletWindow(index);
                                    parent.parent.layer.close(index);
                                    parent.parent.layer.close('${closeIndex}');
                                    parent.parent.layui.table.reload('customTable', {
                                        page: {
                                            curr: 1
                                        }
                                    });
                                    parent.parent.layui.totalFilter.init('customTable');
                                });
                            } else {
                                layer.alert(data.msg);
                            }
                        }
                    })
                });

                function loadTable(data) {
                    table.render({
                        elem: '#fieldList'
                        , data: data
                        , page: false
                        , limit: 10000
                        , cols: [[
                            {field: 'fieldName', title: '列名'}
                            , {field: 'fieldDesc', title: '注释', edit: 'text'}
                            , {
                                field: 'fieldType', title: '类型', width: 150,
                                templet: function (d) {
                                    if (d.fieldType == "varchar") {
                                        return d.fieldType + "(" + d.charLen + ")";
                                    } else if (d.fieldType == "number") {
                                        return d.fieldType + "(" + d.intLen + "," + d.decimalLen + ")";
                                    } else {
                                        return d.fieldType;
                                    }
                                }
                            }
                            , {
                                field: 'isRequired', title: '必填', templet: function (row) {
                                    var html = "<input type='checkbox' lay-skin='primary' name='isRequired'";
                                    if (row.isRequired == 1) {
                                        html += " checked ";
                                    }
                                    html += ">";
                                    return html;
                                }
                            }
                            , {
                                field: 'isList', title: '显示到列表', templet: function (row) {
                                    var html = "<input type='checkbox' lay-skin='primary' name='isList'";
                                    if (row.isList == 1) {
                                        html += " checked ";
                                    }
                                    html += ">";
                                    return html;
                                }
                            }
                            , {
                                field: 'isFlowVar', title: '是否流程变量', templet: function (row) {
                                    var html = "<input type='checkbox' lay-skin='primary' name='isFlowVar'";
                                    if (row.isFlowVar == 1) {
                                        html += " checked ";
                                    }
                                    html += ">";
                                    return html;
                                }
                            }
                            , {title: '管理', toolbar: '#operation', width: 150, align: 'center'}]]
                        , page: false
                        , limit: 1000
                        , done: function (data) {
                            allFields = data.data;
                        }
                    });
                }

                //监听行单击事件
                table.on('row(fieldList)', function (obj) {
                    var data = obj.data;
                    $("#moveUp").on('click', function () {
                        var tr = obj.tr;
                        $(tr).insertBefore($(tr).prev())
                    });
                    $("#moveDown").on('click', function () {
                        var tr = obj.tr;
                        $(tr).insertAfter($(tr).next())
                    });

                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                });
                //点编辑后回显数据
                layui.getFieldValue = function (retFields, isAdd, index) {
                    if (isAdd == 0) {
                        fieldList[index] = retFields;
                    } else {
                        fieldList.push(retFields);
                    }
                    loadTable(fieldList);
                };
                var allFields;
                layui.getAllFields = function () {
                    return allFields;
                };
                var editData = "";
                layui.getEditData = function () {
                    return editData;
                };
                table.on('tool(fieldList)', function (obj) {
                    editData = obj.data;
                    var editFieldName = obj.data.fieldName;
                    switch (obj.event) {
                        case 'edit':
                            var editIndex = $(this).parent().parent().parent().attr("data-index");
                            layer.open({
                                type: 2,
                                title: "编辑列",
                                shade: 0.3,
                                content: serverPath.formPath + setter.formLinkPath + "table/view/addCol?isAdd=0&editIndex=" + editIndex + '&isExternal=1&editFieldName=' + editFieldName,
                                area: ['1000px', '570px']
                            });
                            break;
                    }
                });
                //关闭弹窗
                var index = parent.layer.getFrameIndex(window.name);
                $('#revert').click(function () {
                    parent.layer.close(index);
                })
            });
        </script>
        <style>
            .mainTableRadio .layui-form-radio {
                margin-top: 0;
            }

            .layui-table-body {
                overflow-x: hidden;
            }
        </style>
    </body>
</html>